<script setup>
import { ref } from 'vue'
import { getuserinfo } from '@/api/user.js'
// 定义一个响应式对象来存储用户信息
const userInfo = ref({
  id: null,
  username: '',
  nickname: '',
  email: '',
  user_pic: ''
})

//获取用户信息
const fetchUserInfo = async () => {
  try {
    // 假设有一个方法可以获取用户信息，比如:
    const res = await getuserinfo()
    userInfo.value = {
      id: res.data.id,
      username: res.data.username,
      nickname: res.data.nickname,
      email: res.data.email,
      user_pic: res.data.user_pic
    }
    console.log('用户信息:', res)
  } catch (error) {
    console.error('获取用户信息失败:', error)
  }
}
fetchUserInfo()
// 获得修改后的昵称渲染到顶部
const handlenickname = (nickname) => {
  console.log('得到修改后的nickname', nickname)
  userInfo.value.nickname = nickname
}
</script>
<template>
  <el-menu
    class="el-menu-demo"
    mode="horizontal"
    background-color="#545c64"
    text-color="#fff"
    active-text-color="#ffd04b"
    @select="handleSelect"
  >
    <router-link to="/article/sort"
      ><el-menu-item index="1">文章分类</el-menu-item>文章分类</router-link
    >
    <router-link to="/article/manage"><el-menu-item index="2">文章管理</el-menu-item></router-link>
    <el-sub-menu index="3">
      <template #title>
        <div class="username">
          {{ userInfo.nickname || userInfo.username }}
        </div>
        <el-avatar
          class="useravatar"
          :src="
            userInfo.user_pic
              ? userInfo.user_pic
              : 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png'
          "
        />
      </template>
      <router-link to="/user/data" :userinfo="userInfo" @updatanickname="handlenickname">
        <el-menu-item index="3-1">基本资料</el-menu-item>
      </router-link>

      <router-link to="/user/password"
        ><el-menu-item index="3-2">重置密码</el-menu-item></router-link
      >
    </el-sub-menu>
  </el-menu>

  <router-view :userinfo="userInfo" @updatanickname="handlenickname"></router-view>
</template>

<style scoped>
.username {
  margin: 0 10px;
}
a {
  text-decoration: none; /* 去掉下划线 */
  color: inherit; /* 继承父元素的颜色 */
}
</style>
